package com.dingding.order.core.pay.biz.impl;

import java.math.BigDecimal;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dto.AbstractResponse;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.UserTaxiOrdert;
import com.dingding.common.core.beans.Useraccount;
import com.dingding.facade.account.user.service.IUserAccountService;
import com.dingding.order.code.OrderPayCodeMsg;
import com.dingding.order.code.order.TaxiOrderStatus;
import com.dingding.order.core.pay.biz.IOrderPayService;
import com.dingding.order.core.pay.biz.IPayNotifyService;
import com.dingding.order.core.pay.biz.pay.IPaymentService;
import com.dingding.order.core.pay.dao.IPayUserOrderDao;
import com.dingding.order.core.pay.dao.ITaxiOrderPayDao;
import com.dingding.order.dto.pay.ReqTaxiLinePayDTO;
import com.dingding.order.dto.pay.ReqTaxiOneLinePayDTO;
import com.dingding.order.dto.pay.ResTaxiLinePayDTO;
import com.dingding.order.dto.pay.ResTaxiOneLinePayDTO;
import com.dingding.order.dto.pay.menums.TransactionTypeEnum;

/**
 * 
 * @ClassName: TaxiOrderPayServiceImpl 
 * @Description: 出租车订单支付业务实现
 * @author CHEHAUNBO 
 * @date 2016年7月4日 下午3:24:33
 * @since V2.3.0
 * 
 */
@Component("taxiOneLineOrderPayService")
public class TaxiOneLineOrderPayServiceImpl extends AbstractResponse<ResTaxiOneLinePayDTO, ReqTaxiOneLinePayDTO>
		implements IOrderPayService {

	private Logger log = Logger.getLogger(TaxiOneLineOrderPayServiceImpl.class);

	/**
	 * 出租车订单DAO
	 */
	@Resource(name = "taxiOrderPayDao")
	private ITaxiOrderPayDao taxiOrderDao;

	/**
	 * 订单正式表支付操作DAO
	 */
	@Resource(name = "payUserOrderDao")
	private IPayUserOrderDao payUserOrderDao;

	/**
	 * 订单支付成功后的相关业务操作service
	 */
	@Resource(name = "payNotifyService")
	private IPayNotifyService payNotifyService;

	/**
	 * 用户账户service
	 */
	@Resource(name = "userAccountService")
	private IUserAccountService userAccountService;

	/**
	 * 微信支付生成预订单service
	 */
	@Resource(name = "wechatPayment")
	private IPaymentService wechatPayment;

	/**
	 * 叮币支付service
	 */
	@Resource(name = "dingbiPayment")
	private IPaymentService dingbiPayment;

	/**
	 * 
	 * @Description: 出租车订单线上支付总方法
	 * @param requestJson 客户端请求的JSON数据 
	 * @author CHEHUANBO
	 * @since V2.3.0
	 * 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public String orderPay(String requestJson) {

		// 解析客户端请求的JSON数据
		ReqTaxiOneLinePayDTO reqTaxiOneLinePayDTO = super.parseRequestJson(requestJson);
		ResponseEntity<ResTaxiOneLinePayDTO> responseEntity = new ResponseEntity<ResTaxiOneLinePayDTO>();

		// 验证客户端请求参数是否合法
		if (!super.validateParam(responseEntity, reqTaxiOneLinePayDTO)) {
			return super.responseBeanToJson(responseEntity);
		}
		
		// 获取支付订单信息
		UserTaxiOrdert taxiOrdert = taxiOrderDao.getUserTaxiOrder(reqTaxiOneLinePayDTO.getOid());
		
		// 验证订单是否符合支付条件
		if (!this.getOnLinePayOrderInfo(taxiOrdert, responseEntity)) {
			return super.responseBeanToJson(responseEntity);
		}
		
		// 验证余额是否充足；如果乘客支付选择叮币支付，需要验证用户余额是否充足
		if (!this.validateUserMoney(responseEntity, reqTaxiOneLinePayDTO)) {
			return super.responseBeanToJson(responseEntity);
		}
		
		// 执行扣款
		this.payment(responseEntity, reqTaxiOneLinePayDTO,taxiOrdert);

		return super.responseBeanToJson(responseEntity);

	}

	/**
	 * 
	 * @Title: getPayOrderInfo 
	 * @Description: 获取线上支付订单信息
	 * @param taxiOrderId 订单Id
	 * @author YHQ 
	 * @since V2.3.0
	 * @return void    返回类型
	 * 
	 */
	public boolean getOnLinePayOrderInfo(UserTaxiOrdert taxiOrdert,ResponseEntity<ResTaxiOneLinePayDTO> responseEntity){
		
		if (taxiOrdert == null) { // 订单不存在
			responseEntity.setCode(OrderPayCodeMsg.ORDER_NOT_EXIST.getCode());
			responseEntity.setErrorMessage(OrderPayCodeMsg.ORDER_NOT_EXIST.getMessage());
			responseEntity.setPromptMessage(OrderPayCodeMsg.ORDER_NOT_EXIST.getMessage());
			return false;
		}
		// 由于出租车为后付费方式，所以当司机点击确认到达后订单状态将变为待支付状态，如果不为待支付状态不能执行订单支付
		if (TaxiOrderStatus.ORDER_STATUS_PAID != taxiOrdert.getOrderStatus()) { // 订单不为待支付状态
			responseEntity.setCode(OrderPayCodeMsg.ORDER_STATUS_NOT_WAIT_PAY.getCode());
			responseEntity.setErrorMessage(OrderPayCodeMsg.ORDER_STATUS_NOT_WAIT_PAY.getMessage());
			responseEntity.setPromptMessage(OrderPayCodeMsg.ORER_PAY_FAIL.getMessage());
			return false;
		}
		
		return true;
	}
	
	/**
	 * 
	 * @Title: orderLinePay 
	 * @return  订单线下支付
	 * @author CHEHAUNBO
	 * @since V2.3.0
	 * 
	 */
	@Override
	public String orderLinePay(String requestJson) {

		// 解析客户端请求的JSON数据
		ReqTaxiLinePayDTO reqTaxiLinePayDTO = super.parseRequestJson(requestJson, ReqTaxiLinePayDTO.class);

		ResponseEntity<ResTaxiLinePayDTO> responseEntity = new ResponseEntity<ResTaxiLinePayDTO>();

		// 验证客户端请求参数是否合法
		if (!super.validateParam(responseEntity, reqTaxiLinePayDTO)) {
			return super.responseBeanToJson(responseEntity);
		}
		// 验证订单是否符合支付条件
		if (!this.validateOrder(responseEntity, reqTaxiLinePayDTO.getOid())) {
			return super.responseBeanToJson(responseEntity);
		}

		// 线下支付，无需扣款；直接将出租车临时订单转为正式订单，并将状态转为已完成
		if (!payNotifyService.paySuccessUpdateOrderStatus(reqTaxiLinePayDTO.getOid(),
				TransactionTypeEnum.line.getIndex(), false)) {
			responseEntity.setCode(OrderPayCodeMsg.WEI_CHAT_PAY_FAIL.getCode());
			responseEntity.setErrorMessage(OrderPayCodeMsg.WEI_CHAT_PAY_FAIL.getMessage());
			responseEntity.setPromptMessage(OrderPayCodeMsg.WEI_CHAT_PAY_FAIL.getMessage());
		}

		responseEntity.setCode(HttpStatus.SC_OK);
		return super.responseBeanToJson(responseEntity);

	}

	/**
	 * 
	 * 验证订单是否符合支付条件
	 * 
	 * @Title: validateOrder  
	 * @return boolean true 符合  false 不符合
	 * @author CHEHAUNBO
	 * @since V2.3.0
	 * 
	 */
	private <T> boolean validateOrder(ResponseEntity<T> responseEntity, String taxiOrderId) {

		// 根据出租车订单ID获取订单信息
		UserTaxiOrdert userTaxiOrdert = taxiOrderDao.getUserTaxiOrder(taxiOrderId);

		if (userTaxiOrdert == null) { // 订单不存在
			responseEntity.setCode(OrderPayCodeMsg.ORDER_NOT_EXIST.getCode());
			responseEntity.setErrorMessage(OrderPayCodeMsg.ORDER_NOT_EXIST.getMessage());
			responseEntity.setPromptMessage(OrderPayCodeMsg.ORDER_NOT_EXIST.getMessage());
			return false;
		}
		// 由于出租车为后付费方式，所以当司机点击确认到达后订单状态将变为待支付状态，如果不为待支付状态不能执行订单支付
		if (TaxiOrderStatus.ORDER_STATUS_PAID != userTaxiOrdert.getOrderStatus()) { // 订单不为待支付状态
			responseEntity.setCode(OrderPayCodeMsg.ORDER_STATUS_NOT_WAIT_PAY.getCode());
			responseEntity.setErrorMessage(OrderPayCodeMsg.ORDER_STATUS_NOT_WAIT_PAY.getMessage());
			responseEntity.setPromptMessage(OrderPayCodeMsg.ORER_PAY_FAIL.getMessage());
			return false;
		}

		return true;

	}

	/**
	 * 
	 * 验证用户叮币是否充足
	 * 
	 * 乘客支付，如果选择使用叮币支付需要判断叮币的余额是否充足
	 * 
	 * @Title: validateUserMoney 
	 * @return boolean true 符合  false 不符合
	 * @author CHEHAUNBO
	 * @since V2.3.0
	 * 
	 */
	private boolean validateUserMoney(ResponseEntity<ResTaxiOneLinePayDTO> responseEntity,
			ReqTaxiOneLinePayDTO reqTaxiOneLinePayDTO) {

		// 不使用叮币支付,无需验证叮币余额
		if (reqTaxiOneLinePayDTO.getPayMoney().compareTo(new BigDecimal(0)) <= 0) {
			return true;
		}

		// 获取用户账户信息
		Useraccount useraccount = this.userAccountService.getUserAccount(reqTaxiOneLinePayDTO.getPassengerId());

		// 用户当前账户叮币余额
		if (useraccount != null) {
			BigDecimal remainMoney = useraccount.getCurrencyAmount();
			if (remainMoney.compareTo(reqTaxiOneLinePayDTO.getPayMoney()) >= 0) {
				return true;
			}
		}

		// 余额不足
		responseEntity.setCode(OrderPayCodeMsg.USER_REMAIN_MONEY_NOT_ENOUGH.getCode());
		responseEntity.setErrorMessage(OrderPayCodeMsg.USER_REMAIN_MONEY_NOT_ENOUGH.getMessage());
		responseEntity.setPromptMessage(OrderPayCodeMsg.USER_REMAIN_MONEY_NOT_ENOUGH.getMessage());

		return false;

	}

	/**
	 * 
	 * 扣款
	 * 
	 * 如果需要第三方平台支付需要等待第三方回调才执行扣款操作
	 * 
	 * @Title: payment 
	 * @return boolean true 成功 false 失败
	 * @author CHEHAUNBO
	 * @since V2.3.0
	 * 
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public boolean payment(ResponseEntity<ResTaxiOneLinePayDTO> responseEntity,
			ReqTaxiOneLinePayDTO reqTaxiOneLinePayDTO,UserTaxiOrdert taxiOrdert) {

		try {
			
			//叮币支付金额
			taxiOrdert.setPayMoney(reqTaxiOneLinePayDTO.getPayMoney()); 
			
			// 叮币支付金额大于0
			if (reqTaxiOneLinePayDTO.getPayMoney().compareTo(new BigDecimal(0)) > 0 && reqTaxiOneLinePayDTO.getPayType() == 3) {
				// 叮币支付
				if (dingbiPayment.payment(reqTaxiOneLinePayDTO, responseEntity)) {
					if (reqTaxiOneLinePayDTO.getThirdPartyPayMoney().compareTo(new BigDecimal(0)) <= 0) { // 不使用第三方支付，叮币扣款成功后直接订单完成
						
						// 叮币支付成功后；将临时出租车订单转为正式订单，并将状态改为已完成。
						payNotifyService.paySuccessUpdateOrderStatus(reqTaxiOneLinePayDTO.getOid(),
								TransactionTypeEnum.onLine.getIndex(), false);
					}
				}
			}

			// 存在第三方支付，并且是微信支付执行;注意当前操作并只是在微信平台生成支付预定单。
			if (reqTaxiOneLinePayDTO.getThirdPartyPayMoney().compareTo(new BigDecimal(0)) > 0 && reqTaxiOneLinePayDTO.getPayType() == 2) {
				if (!wechatPayment.payment(reqTaxiOneLinePayDTO, responseEntity)) {
					return false;
				} else {
					
					//第三方支付金额
					taxiOrdert.setAlipayMoney(reqTaxiOneLinePayDTO.getThirdPartyPayMoney()); 
					
					return true;
				}
			}

			ResTaxiOneLinePayDTO resTaxiOneLinePayDTO = new ResTaxiOneLinePayDTO();
			resTaxiOneLinePayDTO.setOid(reqTaxiOneLinePayDTO.getOid());
			resTaxiOneLinePayDTO.setThirdPartyPayMoney(reqTaxiOneLinePayDTO.getThirdPartyPayMoney());
			responseEntity.setResponseBody(resTaxiOneLinePayDTO);

		} catch (Exception e) {
			responseEntity.setCode(OrderPayCodeMsg.ORER_PAY_FAIL.getCode());
			responseEntity.setErrorMessage(OrderPayCodeMsg.ORER_PAY_FAIL.getMessage());
			responseEntity.setPromptMessage(OrderPayCodeMsg.ORER_PAY_FAIL.getMessage());
			log.error("乘客使用叮币支付出现异常！", e);
			return false;
		}

		return true;
	}

}
